package com.atguigu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV1;
import com.atguigu.realtime.bean.TradeTrademarkCategoryUserRefundBean;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.function.DimAsyncFunction;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Collections;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;

/**
 * @Author lzc
 * @Date 2022/6/1 10:21
 */
public class Dws_11_DwsTradeTrademarkCategoryUserRefundWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_11_DwsTradeTrademarkCategoryUserRefundWindow().init(3011,
                                                                    2,
                                                                    "Dws_11_DwsTradeTrademarkCategoryUserRefundWindow",
                                                                    Constant.TOPIC_DWD_TRADE_ORDER_REFUND);
    }
    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1. 解析成bean
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> beanStream = parseBean(stream);
        
        // 2. 补充 tm_id和c3_id
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> beanStreamWithC3AndTm = addTmIdAndC3Id(beanStream);
    
        // 3. 开窗聚合
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> beanStreamWithoutDim = windowAndAggregate(beanStreamWithC3AndTm);
        // 4. 补充维度信息
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> resultStream = addOtherDims(beanStreamWithoutDim);
    
        // 5. 写出到clickhouse中
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink(Constant.CLICKHOUSE_DB, "dws_trade_trademark_category_user_refund_window", TradeTrademarkCategoryUserRefundBean.class));
    }
    
    private SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> addOtherDims(SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> beanStreamWithoutDim) {
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> streamWithTm = AsyncDataStream.unorderedWait(
            beanStreamWithoutDim,
            new DimAsyncFunction<TradeTrademarkCategoryUserRefundBean>() {
            
                @Override
                public void addDim(TradeTrademarkCategoryUserRefundBean input, JSONObject dim) {
                    input.setTrademarkName(dim.getString("TM_NAME"));
                }
            
                @Override
                public String getTableName() {
                    return "dim_base_trademark";
                }
            
                @Override
                public String getDimId(TradeTrademarkCategoryUserRefundBean input) {
                    return input.getTrademarkId();
                }
            },
            120,
            TimeUnit.SECONDS
        );
    
    
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> streamWithC3 = AsyncDataStream.unorderedWait(
            streamWithTm,
            new DimAsyncFunction<TradeTrademarkCategoryUserRefundBean>() {
            
                @Override
                public void addDim(TradeTrademarkCategoryUserRefundBean input, JSONObject dim) {
                    input.setCategory3Name(dim.getString("NAME"));
                    input.setCategory2Id(dim.getString("CATEGORY2_ID"));
                }
            
                @Override
                public String getTableName() {
                    return "dim_base_category3";
                }
            
                @Override
                public String getDimId(TradeTrademarkCategoryUserRefundBean input) {
                    return input.getCategory3Id();
                }
            },
            120,
            TimeUnit.SECONDS
        );
    
    
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> streamWithC2 = AsyncDataStream.unorderedWait(
            streamWithC3,
            new DimAsyncFunction<TradeTrademarkCategoryUserRefundBean>() {
            
                @Override
                public void addDim(TradeTrademarkCategoryUserRefundBean input, JSONObject dim) {
                    input.setCategory2Name(dim.getString("NAME"));
                    input.setCategory1Id(dim.getString("CATEGORY1_ID"));
                }
            
                @Override
                public String getTableName() {
                    return "dim_base_category2";
                }
            
                @Override
                public String getDimId(TradeTrademarkCategoryUserRefundBean input) {
                    return input.getCategory2Id();
                }
            },
            120,
            TimeUnit.SECONDS
        );
    
        return AsyncDataStream.unorderedWait(
            streamWithC2,
            new DimAsyncFunction<TradeTrademarkCategoryUserRefundBean>() {
            
                @Override
                public void addDim(TradeTrademarkCategoryUserRefundBean input, JSONObject dim) {
                    input.setCategory1Name(dim.getString("NAME"));
                }
            
                @Override
                public String getTableName() {
                    return "dim_base_category1";
                }
            
                @Override
                public String getDimId(TradeTrademarkCategoryUserRefundBean input) {
                    return input.getCategory1Id();
                }
            },
            120,
            TimeUnit.SECONDS
        );
    }
    
    private SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> addTmIdAndC3Id(SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> beanStream) {
       return AsyncDataStream.unorderedWait(
            beanStream,
            new DimAsyncFunction<TradeTrademarkCategoryUserRefundBean>(){
                @Override
                public void addDim(TradeTrademarkCategoryUserRefundBean input, JSONObject dim) {
                    input.setCategory3Id(dim.getString("CATEGORY3_ID"));
                    input.setTrademarkId(dim.getString("TM_ID"));
                }
    
                @Override
                public String getTableName() {
                    return "dim_sku_info";
                }
    
                @Override
                public String getDimId(TradeTrademarkCategoryUserRefundBean input) {
                    return input.getSkuId();
                }
            },
            120,
            TimeUnit.SECONDS
        );
    }
    
    private SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> windowAndAggregate(SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> beanStream) {
      return  beanStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<TradeTrademarkCategoryUserRefundBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
            )
            .keyBy(bean-> bean.getUserId() + "_" + bean.getTrademarkId() + "_" + bean.getCategory3Id())
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<TradeTrademarkCategoryUserRefundBean>() {
                    @Override
                    public TradeTrademarkCategoryUserRefundBean reduce(TradeTrademarkCategoryUserRefundBean b1,
                                                                       TradeTrademarkCategoryUserRefundBean b2) throws Exception {
                        b1.getOrderIdSet().addAll(b2.getOrderIdSet());
                        return b1;
                    }
                },
                new ProcessWindowFunction<TradeTrademarkCategoryUserRefundBean, TradeTrademarkCategoryUserRefundBean, String, TimeWindow>() {
                    @Override
                    public void process(String key,
                                        Context ctx,
                                        Iterable<TradeTrademarkCategoryUserRefundBean> elements,
                                        Collector<TradeTrademarkCategoryUserRefundBean> out) throws Exception {
    
                        TradeTrademarkCategoryUserRefundBean bean = elements.iterator().next();
                        bean.setStt(AtguiguUtil.toDateTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.toDateTime(ctx.window().getEnd()));
                        
                        bean.setRefundCount((long) bean.getOrderIdSet().size());
    
                        bean.setTs(System.currentTimeMillis());
                        
                        out.collect(bean);
    
                    }
                }
            );
    }
    
    private SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> parseBean(DataStreamSource<String> stream) {
      return  stream
            .map(json -> {
                JSONObject obj = JSON.parseObject(json);
    
                String skuId = obj.getString("sku_id");
                String userId = obj.getString("user_id");
                String orderId = obj.getString("order_id");
    
                return TradeTrademarkCategoryUserRefundBean.builder()
                    .skuId(skuId)
                    .userId(userId)
                    .orderIdSet(new HashSet<>(Collections.singleton(orderId)))
                    .ts(obj.getLong("ts") * 1000)
                    .build();
            });
    }
}
